Quick Lesson on JavaScript and Code Core Conceps!!!

What are Time Complexities and Space/Memory Complexities in Code?

What do algorithms and data structures mean in code?

/*
# JavaScript Data Structures & Algorithms Lesson

This lesson will teach you about basic data structures, algorithms, and their **time & memory complexities** in JavaScript. We will include explanations, examples, and exercises for hands-on practice.

---

## 1. Arrays

Arrays store elements in a sequence. They allow random access using an index.

let arr = [1, 2, 3, 4];
console.log(arr[2]); // Output: 3 '*/


Common Operations & Time Complexity:

Operation Time Complexity Access by index O(1) Append element O(1) amortized Insert at start O(n) Delete at index O(n)

%%js

let arr = [1, 2, 3, 4];
// TODO: Insert 5 at the start
console.log(arr); // Expected: [5, 1, 2, 3, 4]

<IPython.core.display.Javascript object>

2. Loops and Iteration Complexity

Iterating over an array:

%%js

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Iterating once → O(n)

Nested loops → O(n^2), etc. Exercise 2: Count even numbers in an array

%%js

let arr = [1, 2, 3, 4, 5, 6];
let count = 0;
// TODO: Loop through arr and count even numbers
console.log(count); // Expected: 3

3. Functions & Simple Algorithms

Example: Sum of an array

%%js

function sumArray(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}
console.log(sumArray([1, 2, 3])); // 6

Time Complexity: O(n) Memory Complexity: O(1) (constant extra memory)

Exercise 3: Write a function to find the maximum element in an array

%%js

function maxElement(arr) {
  // TODO: return the maximum element
}
console.log(maxElement([5, 2, 9, 1])); // Expected: 9

4. Objects (Hash Maps)

Objects store key-value pairs.

%%js

let obj = {a: 1, b: 2};
console.log(obj["a"]); // 1
obj["c"] = 3; // Add a key
delete obj["b"]; // Delete a key

Common Operations & Time Complexity:

Operation Time Complexity Access key O(1) Insert key O(1) Delete key O(1)

Exercise 4: Fill in the code to count frequency of letters

%%js

let str = "hello";
let freq = {};
// TODO: Count frequency of each letter in str
console.log(freq); // Expected: { h: 1, e: 1, l: 2, o: 1 }

%%js

function example1(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}

function example2(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      console.log(i, j);
    }
  }
}
// Identification of Time Complexities

Challenge - Reverse an Array

%%js

let arr = [1, 2, 3, 4];
// TODO: Reverse arr in-place.
console.log(arr); // Expected: [4, 3, 2, 1]

Summary:

Arrays: O(1) access, O(n) insert/delete

Loops: Analyze iterations for time complexity

Objects: Key-value pairs, O(1) operations

Always analyze your algorithm for time and memory usage

Memory Complexity vs Run-Time Complexity - How much extra memory and time/operations you use with respect to the input